// 工具函数

// 日期格式化
export const formatDate = (date, format = 'yyyy-MM-dd HH:mm:ss') => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('yyyy', year)
    .replace('MM', month)
    .replace('dd', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

// 价格格式化
export const formatPrice = (price, showSymbol = true) => {
  if (price === null || price === undefined) return showSymbol ? '¥0.00' : '0.00'
  const formattedPrice = Number(price).toFixed(2)
  return showSymbol ? `¥${formattedPrice}` : formattedPrice
}

// 数字格式化（千分位）
export const formatNumber = (num) => {
  if (num === null || num === undefined) return '0'
  return Number(num).toLocaleString('zh-CN')
}

// 防抖函数
export const debounce = (func, wait = 300) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 节流函数
export const throttle = (func, limit = 300) => {
  let inThrottle
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 获取URL参数
export const getQueryParam = (name) => {
  const urlParams = new URLSearchParams(window.location.search)
  return urlParams.get(name)
}

// 设置URL参数
export const setQueryParam = (name, value) => {
  const urlParams = new URLSearchParams(window.location.search)
  urlParams.set(name, value)
  window.history.replaceState({}, '', `${window.location.pathname}?${urlParams}`)
}

// 删除URL参数
export const removeQueryParam = (name) => {
  const urlParams = new URLSearchParams(window.location.search)
  urlParams.delete(name)
  window.history.replaceState({}, '', `${window.location.pathname}${urlParams.toString() ? '?' + urlParams.toString() : ''}`)
}

// 检测是否为移动端
export const isMobile = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

// 检测是否为微信环境
export const isWechat = () => {
  return /micromessenger/i.test(navigator.userAgent)
}

// 检测是否为支付宝环境
export const isAlipay = () => {
  return /alipayclient/i.test(navigator.userAgent)
}

// 生成随机字符串
export const randomString = (length = 8) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 深度合并对象
export const deepMerge = (target, source) => {
  if (typeof target !== 'object' || target === null) {
    return source
  }
  
  if (typeof source !== 'object' || source === null) {
    return target
  }
  
  const merged = { ...target }
  
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (typeof source[key] === 'object' && source[key] !== null && typeof merged[key] === 'object' && merged[key] !== null) {
        merged[key] = deepMerge(merged[key], source[key])
      } else {
        merged[key] = source[key]
      }
    }
  }
  
  return merged
}

// 数组去重
export const uniqueArray = (array, key) => {
  if (!array || !array.length) return []
  
  if (key) {
    const seen = new Map()
    return array.filter(item => {
      const k = item[key]
      return seen.has(k) ? false : seen.set(k, true)
    })
  } else {
    return [...new Set(array)]
  }
}

// 数组分组
export const groupArray = (array, key) => {
  if (!array || !array.length) return {}
  
  return array.reduce((groups, item) => {
    const k = item[key]
    if (!groups[k]) {
      groups[k] = []
    }
    groups[k].push(item)
    return groups
  }, {})
}

// 计算两点之间的距离
export const calculateDistance = (lat1, lon1, lat2, lon2) => {
  const R = 6371 // 地球半径（公里）
  const dLat = deg2rad(lat2 - lat1)
  const dLon = deg2rad(lon2 - lon1)
  const a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon / 2) * Math.sin(dLon / 2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  const distance = R * c // 距离（公里）
  return distance
  
  function deg2rad(deg) {
    return deg * (Math.PI / 180)
  }
}

// 滚动到页面顶部
export const scrollToTop = (behavior = 'smooth') => {
  window.scrollTo({
    top: 0,
    behavior
  })
}

// 滚动到底部
export const scrollToBottom = (behavior = 'smooth') => {
  window.scrollTo({
    top: document.documentElement.scrollHeight,
    behavior
  })
}

// 复制文本到剪贴板
export const copyToClipboard = async (text) => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
    } else {
      // 回退方法
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
    }
    return true
  } catch (error) {
    console.error('复制失败:', error)
    return false
  }
}

// 下载文件
export const downloadFile = (url, filename) => {
  const link = document.createElement('a')
  link.href = url
  link.download = filename || 'download'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 校验手机号码
export const validatePhone = (phone) => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}

// 校验邮箱
export const validateEmail = (email) => {
  const reg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/i
  return reg.test(email)
}

// 校验身份证号
export const validateIdCard = (idCard) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return reg.test(idCard)
}

// 获取文件大小格式化
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}